package cn.com.infcn.monitor.task.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import cn.com.infcn.monitor.bean.IFCCpu;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * 获取系统cpu信息，返回一个cpu信息的数组
 * 
 * @author jjs
 *
 */
public class CpuTask implements BaseTask{

	private static final Logger LOGGER = Logger.getLogger(CpuTask.class);


	@Override
	public List<IFCCpu> execute() throws Exception {
		return cpu();
	}

	private List<IFCCpu> cpu() throws SigarException {

		try {
			Sigar sigar = new Sigar();
			CpuInfo cpuInfos[] = sigar.getCpuInfoList();
			CpuPerc cpuPercs[] = sigar.getCpuPercList();
			List<IFCCpu> ifcCpus = new ArrayList<IFCCpu>();

			for (int i = 0; i < cpuInfos.length; i++) {// 不管是单块CPU还是多CPU都适用
				// cpu 信息
				CpuInfo cpuInfo = cpuInfos[i];
				// cpu 使用率信息
				CpuPerc cpuPerc = cpuPercs[i];
				IFCCpu ifcCpu = new IFCCpu();
				IFCBeanUtils.copyProperties(cpuInfo, ifcCpu);
				IFCBeanUtils.copyProperties(cpuPerc, ifcCpu);

				ifcCpus.add(ifcCpu);
			}

			return ifcCpus;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}
		return null;
	}

	
	public static void main(String[] args) throws SigarException {
		CpuTask t = new CpuTask();
		List<IFCCpu> cpus = t.cpu();
		IFCCpu cpu = cpus.get(0);
		System.out.println(cpu.getMhz());
	}

}
